<template>
  <div class="add-size">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑尺寸' : '添加尺寸' }}</h2>
      <p>{{ isEdit ? '修改尺寸信息' : '创建新的尺寸规格' }}</p>
    </div>
    
    <div class="content-section">
      <form @submit.prevent="submitForm" class="size-form">
        <div class="form-row">
          <div class="form-group">
            <label for="sizeName">尺寸名称 *</label>
            <input 
              type="text" 
              id="sizeName" 
              v-model="form.name" 
              placeholder="请输入尺寸名称"
              required
            >
          </div>
          <div class="form-group">
            <label for="sizeValue">尺寸值 *</label>
            <input 
              type="text" 
              id="sizeValue" 
              v-model="form.value" 
              placeholder="请输入尺寸值"
              required
            >
          </div>
        </div>
        
        <div class="form-row">
          <div class="form-group">
            <label for="sizeUnit">单位 *</label>
            <select id="sizeUnit" v-model="form.unit" required>
              <option value="">请选择单位</option>
              <option value="码">码</option>
              <option value="US">US</option>
              <option value="EU">EU</option>
              <option value="UK">UK</option>
              <option value="cm">cm</option>
              <option value="inch">inch</option>
              <option value="mm">mm</option>
            </select>
          </div>
          <div class="form-group">
            <label for="sizeCategory">尺寸分类 *</label>
            <select id="sizeCategory" v-model="form.categoryId" required>
              <option value="">请选择分类</option>
              <option 
                v-for="type in types" 
                :key="type.type_id" 
                :value="type.type_id"
                style="color: #374151; background-color: white;"
              >
                {{ type.type_name }}
              </option>
            </select>
          </div>
        </div>
        
        <div class="form-row">
          <div class="form-group">
            <label for="sizeColor">适用颜色</label>
            <select id="sizeColor" v-model="form.colorId">
              <option value="">请选择颜色</option>
              <option 
                v-for="color in colors" 
                :key="color.color_id" 
                :value="color.color_id"
                style="color: #374151; background-color: white;"
              >
                {{ color.color_name }}
              </option>
            </select>
          </div>
        </div>
        
        <div class="form-row">
          <div class="form-group">
            <label for="sortOrder">排序</label>
            <input 
              type="number" 
              id="sortOrder" 
              v-model.number="form.sortOrder" 
              placeholder="排序值，数字越小越靠前"
              min="0"
            >
          </div>
          <div class="form-group">
            <label for="status">状态</label>
            <select id="status" v-model="form.status">
              <option value="active">启用</option>
              <option value="inactive">禁用</option>
            </select>
          </div>
        </div>
        
        <div class="form-group full-width">
          <label for="description">描述</label>
          <textarea 
            id="description" 
            v-model="form.description" 
            placeholder="请输入尺寸描述"
            rows="3"
          ></textarea>
        </div>
        
        <div class="form-group full-width">
          <label for="measurements">详细尺寸</label>
          <textarea 
            id="measurements" 
            v-model="form.measurements" 
            placeholder="请输入详细尺寸信息，如：长度、宽度、高度等"
            rows="3"
          ></textarea>
        </div>
        
        <div class="form-actions">
          <button type="button" class="btn btn-secondary" @click="goBack">
            <i class="icon">←</i>
            返回
          </button>
          <button type="button" class="btn btn-outline" @click="resetForm">
            <i class="icon">🔄</i>
            重置
          </button>
          <button type="submit" class="btn btn-primary">
            <i class="icon">💾</i>
            {{ isEdit ? '更新' : '保存' }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'AddSize',
  props: {
    editData: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      form: {
        name: '',
        value: '',
        unit: '',
        categoryId: '',
        colorId: '',
        sortOrder: 0,
        status: 'active',
        description: '',
        measurements: ''
      },
      types: [],
      colors: []
    };
  },
  computed: {
    isEdit() {
      return this.editData && this.editData.size;
    }
  },
  mounted() {
    if (this.isEdit) {
      this.loadEditData();
    }
    // 加载分类和颜色数据
    this.loadTypes();
    this.loadColors();
  },
  methods: {
    loadEditData() {
      const { size, category } = this.editData;
      this.form = {
        name: size.name || '',
        value: size.value || '',
        unit: size.unit || '',
        categoryId: category.id.toString() || '',
        sortOrder: size.sortOrder || 0,
        status: size.status || 'active',
        description: size.description || '',
        measurements: size.measurements || ''
      };
    },
    submitForm() {
      if (this.validateForm()) {
        if (this.isEdit) {
          this.updateSize();
        } else {
          this.createSize();
        }
      }
    },
    validateForm() {
      if (!this.form.name.trim()) {
        this.showToast('请输入尺寸名称', 'error');
        return false;
      }
      if (!this.form.value.trim()) {
        this.showToast('请输入尺寸值', 'error');
        return false;
      }
      if (!this.form.unit) {
        this.showToast('请选择单位', 'error');
        return false;
      }
      if (!this.form.categoryId) {
        this.showToast('请选择尺寸分类', 'error');
        return false;
      }
      return true;
    },
    createSize() {
      // 模拟创建尺寸
      console.log('创建尺寸:', this.form);
      this.showToast('尺寸创建成功！', 'success');
      setTimeout(() => {
        this.goBack();
      }, 1500);
    },
    updateSize() {
      // 模拟更新尺寸
      console.log('更新尺寸:', this.form);
      this.showToast('尺寸更新成功！', 'success');
      setTimeout(() => {
        this.goBack();
      }, 1500);
    },
    resetForm() {
      if (this.isEdit) {
        this.loadEditData();
      } else {
        this.form = {
          name: '',
          value: '',
          unit: '',
          categoryId: '',
          colorId: '',
          sortOrder: 0,
          status: 'active',
          description: '',
          measurements: ''
        };
        this.showToast('表单已重置', 'info');
      }
    },
    goBack() {
        this.$emit('navigate', 'SizeList');
      },
      async loadTypes() {
      try {
        console.log('开始加载分类数据...')
        const response = await fetch('http://localhost:8080/api/types')
        const data = await response.json()
        console.log('分类API响应:', data)
        
        // 正确处理后端返回的数据结构
        if (data && data.code === 200) {
          this.types = data.data || []
        } else {
          this.types = data || []
        }
        console.log('处理后的分类数据:', this.types)
      } catch (error) {
        console.error('加载分类列表失败:', error)
        // 使用示例数据作为后备
        this.types = [
          { type_id: 1, type_name: '篮球鞋', status: 1 },
          { type_id: 2, type_name: '跑步鞋', status: 1 },
          { type_id: 3, type_name: '休闲鞋', status: 1 },
          { type_id: 4, type_name: '足球鞋', status: 0 }
        ]
        console.log('使用后备分类数据:', this.types)
      }
    },
    
    async loadColors() {
      try {
        console.log('开始加载颜色数据...')
        const response = await fetch('http://localhost:8080/api/colors')
        const data = await response.json()
        console.log('颜色API响应:', data)
        
        // 正确处理后端返回的数据结构
        if (data && data.code === 200) {
          this.colors = data.data || []
        } else {
          this.colors = data || []
        }
        console.log('处理后的颜色数据:', this.colors)
      } catch (error) {
        console.error('加载颜色列表失败:', error)
        // 使用示例数据作为后备
        this.colors = [
          { color_id: 1, color_name: '黑红', status: 1 },
          { color_id: 2, color_name: '白色', status: 1 },
          { color_id: 3, color_name: '红色', status: 1 },
          { color_id: 4, color_name: '蓝白', status: 0 }
        ]
        console.log('使用后备颜色数据:', this.colors)
      }
    },

    showToast(message, type = 'info') {
      const toast = document.createElement('div');
      toast.className = `toast toast-${type}`;
      toast.textContent = message;
      toast.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 12px 20px;
        background: ${type === 'success' ? '#28a745' : type === 'error' ? '#dc3545' : '#17a2b8'};
        color: white;
        border-radius: 4px;
        z-index: 9999;
        animation: slideIn 0.3s ease;
      `;
      document.body.appendChild(toast);
      setTimeout(() => {
        toast.style.animation = 'slideOut 0.3s ease';
        setTimeout(() => document.body.removeChild(toast), 300);
      }, 3000);
    }
  }
};
</script>

<style scoped>
.add-size {
  padding: 0;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #2c3e50;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #6c757d;
  font-size: 14px;
}

.content-section {
  background: white;
  border-radius: 12px;
  padding: 32px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.size-form {
  max-width: 800px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  margin-bottom: 24px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group.full-width {
  grid-column: 1 / -1;
}

.form-group label {
  margin-bottom: 8px;
  font-weight: 500;
  color: #374151;
  font-size: 14px;
}

.form-group input,
.form-group select,
.form-group textarea {
  padding: 12px 16px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s ease;
  background: #f9fafb;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #667eea;
  background: white;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-group textarea {
  resize: vertical;
  min-height: 80px;
}

.form-actions {
  display: flex;
  gap: 16px;
  justify-content: flex-end;
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #e5e7eb;
}

.btn {
  display: inline-flex;
  align-items: center;
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  text-decoration: none;
}

.btn .icon {
  margin-right: 8px;
  font-size: 16px;
}

.btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background: #5a6268;
  transform: translateY(-2px);
}

.btn-outline {
  background: transparent;
  color: #667eea;
  border: 2px solid #667eea;
}

.btn-outline:hover {
  background: #667eea;
  color: white;
  transform: translateY(-2px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-row {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .btn {
    justify-content: center;
  }
}

/* 动画效果 */
@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

@keyframes slideOut {
  from {
    transform: translateX(0);
    opacity: 1;
  }
  to {
    transform: translateX(100%);
    opacity: 0;
  }
}
</style>